package map;


public class LinkedListMap<K,V> implements Map<K,V> {
    private  class Node{
        public K key;
        public V value;
        public Node next;

        public Node(K key,V value,Node next){
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key){
            this(key,null,null);
        }

        public Node(){
            this(null,null,null);
        }

        @Override
        public String toString(){
            return key.toString();
        }
    }

    private int size;

    private Node dummyHead;

    //map的构造函数
    public LinkedListMap(){
        dummyHead = new Node();
        size = 0;
    }


    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if(node != null){
            node.value =value;
        } else {
            dummyHead.next = new Node(key,value,dummyHead.next);
            size++;
        }
    }

    @Override
    public void set(K key, V value) {
        //已有值，进行重新设置值
        Node node = getNode(key);
        if(node != null){
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {
        if(!contains(key)){
            return null;
        }

        Node prev = dummyHead;

        while(prev.next != null){
            if(key.equals(prev.next.key)){
                break;
            }
            prev = prev.next;
        }
        if(prev.next != null){
            //进行删除操作
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            return delNode.value;
        }
        return null;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key)!= null;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        if(node != null){
            return node.value;
        }
        return null;
    }



    //私有的辅助函数
    private Node getNode(K key){
        Node prev = dummyHead.next;
        while(prev != null){
            if(key.equals(prev.key)){
                return prev;
            }
            prev = prev.next;
        }
        return null;
    }

}
